package concurrent.chapter02_01;

import org.omg.PortableServer.THREAD_POLICY_ID;

/**
 * @Comment:交替打印任务
 * @Author:Shem
 * @Date:2019/5/25
 */
public class PrintTask implements Runnable {

    private volatile int order = 0;
    private volatile int loopCount = 1;

    private int loopCountTotal;
    private String[] threadNames;

    public PrintTask(String[] threadNames, int loopCountTotal) {
        this.loopCountTotal = loopCountTotal;
        this.threadNames = threadNames;
    }

    @Override
    public void run() {
        String currentThreadName = Thread.currentThread().getName();
        while (loopCount <= loopCountTotal) {
            if (threadNames[order].equals(currentThreadName)) {
                synchronized (this) {

                    System.out.println(String.format("线程名：%s，第%s次循环，打印数字：%s", currentThreadName, loopCount, order));
                    if (order < threadNames.length - 1) {
                        order++;
                    } else {
                        order = 0;
                        loopCount++;
                    }
                    this.notifyAll();
                    try {
                        if (loopCount <= loopCountTotal)
                            this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
